function readFileImg (file, resolve, reject) {
  // 读取图片信息并展示
  const reader = new FileReader() // 读取文件实例
  reader.readAsDataURL(file) // 将文件读取为 DataURL
  reader.onload = () => { // 文件读取成功完成时触发
    const img = new Image()
    img.src = reader.result // 文件一旦开始读取，无论成功或失败，实例的 result 属性都会被填充。如果读取失败，则 result 的值为 null ，否则即是读取的结果，绝大多数的程序都会在成功读取文件的时候，抓取这个值。
    img.onload = () => {
      // this.imgSrc = img.src // 以上是将选择的图片展示出来
      const originWidth = img.naturalWidth // 获取图片原始大小
      const originHeight = img.naturalHeight
      const originSize = file.size / 1024 // 计算图片多少kb
      compressEvent(file, img, originSize, originWidth, originHeight, resolve, reject)
    }
  }
  reader.onerror = function (error) {
    console.log(`error: ${error}`)
  }
}
function compressEvent (file, img, originSize, originWidth, originHeight, resolve, reject) {
  // 将图片绘制到canvas上进行压缩
  const canvas = document.createElement('canvas')
  const context = canvas.getContext('2d')
  const maxSize = 1024
  if (originSize <= maxSize) {
    const fd = new FormData()
    fd.append('image', file)
    // this.formData = fd
    resolve(fd)
    return false
  }
  let mul = maxSize / originSize
  mul = mul.toFixed(2)
  const targetWidth = originWidth
  const targetHeight = originHeight
  canvas.width = targetWidth
  canvas.height = targetHeight
  context.clearRect(0, 0, targetWidth, targetHeight) // 清除画布
  context.drawImage(img, 0, 0, targetWidth, targetHeight) // 画图

  const dataURL = canvas.toDataURL('image/jpeg', mul) // 将其转化成base64字符串

  const files = dataURLtoFile(dataURL, 'image/jpeg') // 将base64转换为file文件

  const fd = new FormData()
  fd.append('image', files)
  // this.formData = fd
  resolve(fd)
}
function dataURLtoFile (dataurl, filename) {
  // 将base64转换为file文件
  const arr = dataurl.split(',')
  // const mime = arr[0].match(/:(.*?);/)[1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  // console.log(new File([u8arr], filename))
  return new File([u8arr], filename)
}

// function dataURItoBlob (dataURI) {
//   // base64格式转化为blob对象
//   const byteString = atob(dataURI.split(',')[1])

//   const mimeString = dataURI
//     .split(',')[0]
//     .split(':')[1]
//     .split(';')[0]

//   const ab = new ArrayBuffer(byteString.length)
//   const ia = new Uint8Array(ab)
//   for (let i = 0; i < byteString.length; i++) {
//     ia[i] = byteString.charCodeAt(i)
//   }

//   return new Blob([ab], { type: mimeString })
// }

export default readFileImg
